#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include "sort.h"
#include "words.h"

static const int INDEX_FIRST_FILE = 2;

const char* modifiers = "hVbs";

static struct option long_options[] = {
		{ "help", no_argument, 0, 'h' },
		{ "version", no_argument, 0, 'V' },
		{ "bubble", no_argument, 0, 'b' },
		{ "sel", no_argument, 0, 's' },
		{ 0, 0, 0, 0 }
};

static void
version()
{
	(void)fprintf(stdout,"Organizacion de Computadoras - 6620\n\t\tTP0 - Version 1.0 \n");
}

static void
help()
{
	(void)fprintf(stdout, "usage: tp0 [OPTIONS] [file...]\n");
	(void)fprintf(stdout, "\t\t -h, --help             display this help and exit.\n");
	(void)fprintf(stdout, "\t\t -V, --version          display version information and exit.\n");
	(void)fprintf(stdout, "\t\t -b, --bubble           use the bubblesort algorithm.\n");
	(void)fprintf(stdout, "\t\t -s, --sel              use the shellsort algorithm.\n");

	exit(1);
}

int main(int argc,char* argv[]){

	int option_index = 0;
	int ch;

	int isBubblesort, isShellSort = 0;

	while ((ch = getopt_long(argc, argv, modifiers, long_options, &option_index))!= -1)
		switch((char)ch) {
			case 'V':
				version();
				break;
			case 'b':
				isBubblesort = 1; // deberia terminar con una opcion?
				break;
			case 's':
				isShellSort = 1; // deberia terminar con una opcion?
				break;
			case 'h':
				help();
				exit(0);
				break;
			default:
				help();
				exit(1);
			}

	// index to first file
	int i = INDEX_FIRST_FILE;

	// Default sort method
	if (!isBubblesort&&!isShellSort)
	{
		isBubblesort = 1;
		i =  INDEX_FIRST_FILE - 1;
	}

	// Number of files
	int nFiles = argc - i;

	// Si no hay archivos
	if (nFiles <= 0)
	{
		help();
		exit(1);
	}

	// Points to the first file name
	char** filesNames = &argv[i];

	char** words = NULL;

	int nWords = ReadWordsFromFiles(filesNames, nFiles, words);

	if (isBubblesort && nWords)
	{
		bubblesort(words,nWords);
	}
	else if (isShellSort && nWords)
	{
		shellsort(words,nWords);
	}
	else
	{
		// no se pudo leer ningun archivo
		exit(1);
	}

	if (words)
		FreeWords(words, nWords);

	exit(0);

}
